Filters = {
	init: function(activeId) {
		$('#filters > div:first-child span').click(function(){
			$('#filters').toggleClass('collapse');
			var collapsed = $('#filters').hasClass('collapse');
			$(this).toggleClass('ui-icon-triangle-1-s',!collapsed);
			$(this).toggleClass('ui-icon-triangle-1-e',collapsed);
			Filters.refresh(collapsed);
		});
		$('#filters .tabs').tabs({
			activate: function(e, ui) {
				if ($(ui.newTab).hasClass('new-filter')) {
					Filters.add();
				}
			}
		});
		$('#filters .find').button().click(function(){ Filters.apply(); });
		$('#filters .cancel').button().click(function(){ Filters.cancel(); });
		
		if (!filters.length) {
			Filters.add();
		} else {
			$.each(filters,function(i,f){
				Filters.add(f[0],f[1],f[2],f.fields);
			});
			if (activeId) {
				var tab = $('#filters .tabs > div[data-stored-id='+activeId+']');
				Filters.__active(tab);
				$('#filters .tabs').tabs('option','active',$('#filters .tabs > div').index(tab)-1);
			}
		}
		$('#filters > div:first-child span').click();
	},
	refresh : function(collapsed) {
		if (collapsed) {
			var buttons = $('#filters .buttons');
			buttons.html('');
			$('#filters .tabs > ul > li:not(:last-child) > a').each(function(i){
				buttons.append( 
					$('<button>').html($(this).html()).attr('data-tab_num',i).button().toggleClass('a',$(this).parent().hasClass('a')).click(function(){
						if ($(this).hasClass('a')) {
							Filters.cancel();
						} else {
							$('#filters .tabs').tabs('option','active',i);
							Filters.apply();
						}
						Filters.refresh(true);
					})
				);
			});
		}
	},
	add: function(storedId,name,active,fields) {
		var num = $('#filters .tabs').attr('data-next-id');
		if (typeof num =='undefined') {
			num = 1;
		}
		$('#filters .tabs').attr('data-next-id',parseInt(num)+1);
		var tab = $('<div>').attr('id','filter'+num).attr('data-stored-id',storedId?storedId:0);
		$('#filters .tabs ul .new-filter').before( 
			$('<li>')
				.append( $('<span>').addClass('ui-icon ui-icon-check') )
				.append( $('<a>').attr('href','#filter'+num).html(name ? name : 'Фильтр'+num) )
				.append( $('<span>').addClass('ui-icon ui-icon-close').click(function(){ Filters.del(tab); }) )
		);
		tab.append( $('#filter_templates .filter_tools').clone() ).append($('<table>').append('<tbody>'));
		tab.find('.filter_fields').menu();
		tab.find('.filter_fields li').click(function(){
			if ($(this).hasClass('a')) {
				if (tab.find('tr').length>1) {
					Filters.rem_field($(this).closest('.ui-tabs-panel'),$(this).attr('data-name'));
				}
			} else {
				Filters.add_field($(this).closest('.ui-tabs-panel'), $(this).attr('data-title'), $(this).attr('data-name'), $(this).attr('data-type'));
			}
			$(this).closest('ul').hide();
		});
		tab.find('.add_field').button({
			icons: {
	        	primary: "ui-icon-plus",
				secondary: "ui-icon-triangle-1-s"
			},
			text: false
		}).click(function(){
			var menu = $(this).parent().find('.filter_fields').show().position({
				my: 'left top',
				at: 'left bottom',
				of: this
			});
			$(document).one('click', function() { menu.hide(); });
          return false;
		});
		tab.find('.save').button({
			icons: { primary: "ui-icon-disk" },
			text: false
		}).click(function(){
			$('#save_filter_dialog').dialog({
				modal: true,
				open : function() {
					$(this).find('input[name=name]').val( $('#filters .tabs ul li a[href=#'+tab.attr('id')+']').html() );
				},
				buttons: {
					'Сохранить': function() {
						Filters.save($('#save_filter_dialog input[name=name]').val());
						$('#save_filter_dialog').dialog('close');
					},
					'Отменить': function() {
						$('#save_filter_dialog').dialog('close');
					}
				}
			})
		});
		$('#filters .tabs').append(tab).tabs('refresh').tabs('option','active',$('#filters .tabs > div').length-2);
		if (!fields) {
			Filters.add_first_field(tab);			
		} else {
			$.each(fields,function(i,f){
				Filters.add_field(tab,f.title,f[1],f.type_id,f[2],f[3])
			});
		}
	},
	add_field: function(tab,title,name,fieldtype,filtertype,val) {
		if (fieldtype=='text' || fieldtype=='html') {
			fieldtype = 'string';
		}
		var tr = $('#filter_templates table tr[data-type='+fieldtype+']').clone().attr('data-field',name);
		tr.find('td:first-child').html(title);
		tr.find('input[type=text]').addClass('ui-corner-all');
		tr.append($('<td>').append($('<button>').addClass('rm').html('Удалить')));
		tr.find('.rm').button({
			icons: { primary: "ui-icon-minus" },
			text: false
		}).click(function(){
			Filters.rem_field($(this).closest('.ui-tabs-panel'),$(this).closest('tr').attr('data-field'));
		});
		tab.find('table tbody').append(tr);
		tr.find('select').selectmenu({ width:'auto' });
		tab.find('.filter_fields li[data-name='+name+']').addClass('a');
		tab.find('.rm').toggle(tab.find('tr').length > 1);
		if (filtertype) {
			tr.find('select[name=type]').val(filtertype).selectmenu('refresh');
		}
		if (val) {
			tr.find('[name=value]').val(val);
		}
	},
	add_first_field: function(tab) {
		var f = tab.find('.filter_fields li[data-type=string]');
		if (!f.length) {
			f = tab.find('.filter_fields li');
		}
		f = f.first();
		Filters.add_field(tab,f.attr('data-title'),f.attr('data-name'),f.attr('data-type'));
	},
	apply: function() {
		var tab = $('#filters .tabs > div:eq(' + (parseInt($('#filters .tabs').tabs('option','active'))+1) + ')');
		var filter = {};
		tab.find('tr').each(function(){
			filter[$(this).attr('data-field')] = [
				$(this).find('input[name=value]').length ? $(this).find('input[name=value]').val() : null,
				$(this).find('select[name=type]').val()
			];
			grid.filter = filter;
			grid.refresh();
		});
		this.__active(tab);
	},
	cancel: function() {
		$('#filters .tabs > div').removeClass('a');
		$('#filters .tabs ul > li').removeClass('a');
		$('#filters .cancel').button('option','disabled',true);
		grid.filter = {};
		grid.refresh();
	},
	save: function(nm) {
		var tab = $('#filters .tabs > div:visible');
		var pane = $('#filters .tabs ul li a[href=#'+tab.attr('id')+']');
		nm = nm.length ? nm : pane.html();
		var filter = {
			id: tab.attr('data-stored-id'),
			view_id: viewId,
			name: nm,
			active: tab.hasClass('a') ? 1 : 0
		};
		var fields = [];
		$.each(tab.find('table tr'),function(i,tr){
			fields.push({
				field_name: $(tr).attr('data-field'),
				filter_type: $(tr).find('select[name=type]').val(),
				filter_value: $(tr).find('[name=value]').length ? $(tr).find('[name=value]').val() : null
			});
		});
		call('admin.doRelatedActions',{id1:'add_view_filter', params1:filter, id2:'add_view_filter_field', bulkParams2:fields, idName:'filter_id' }).done(function(filterId){  
			tab.attr('data-stored-id', filterId).find('.del').show();
			pane.html(nm);
		});
	},
	del: function(tab) {
		confirmBox(
			'Вы уверены, что хотите удалить фильтр?',
			'Подтвердите удаление',
			function() {
				if (tab.attr('data-stored-id')) {
					call('admin.doAction',{id:'del_view_filter',params:{ id:tab.attr('data-stored-id') }}).done(function(){
						Filters.__del(tab);
					});
				} else {
					Filters.__del(tab);
				}
			}
		);
	},	
	rem_field: function(tab,name) {
		tab.find('.filter_fields li[data-name='+name+']').removeClass('a');
		tab.find('tr[data-field='+name+']').remove();
		tab.find('.rm').toggle(tab.find('tr').length > 1);
	},
	__del: function(tab) {
		if (tab.hasClass('a')) {
			Filters.cancel();
		}
		$('#filters .tabs ul li a[href=#'+tab.attr('id')+']').closest('li').remove();
		tab.remove();
		$('#filters .tabs').tabs('refresh');
		if ($('#filters .tabs > div').length==1) {
			Filters.add();
		}
	},
	__active: function(tab) {
		$('#filters .tabs > div').removeClass('a');
		tab.addClass('a');
		$('#filters .tabs > ul > li').removeClass('a');
		$('#filters .tabs > ul > li > a[href=#'+tab.attr('id')+']').closest('li').addClass('a');
		$('#filters .cancel').button('option','disabled',false);
	}
};

Settings = {
	open: function() {
		$('#list_settings').dialog({
			modal: true,
			width: 500,
			create : function() {
				var dlg = $(this);
				var visible = dlg.find('.visible select');
				visible.change(function(){
					dlg.find('.up,.down,.del').button('option','disabled',$(this).val()==null);
					var selected = $(this).find(':selected');
					dlg.find('.up').button('option','disabled',selected.is(':first-child'));
					dlg.find('.down').button('option','disabled',selected.is(':last-child'));
				});
				var other = dlg.find('.other select');
				other.change(function(){
					dlg.find('.add').button('option','disabled',$(this).val()==null);
				});
				var sortBy = dlg.find('.sort_field');
				$.each(view.allfields,function(){
					sortBy.append($('<option></option>').attr('value',this.name).html(this.title));
				});
				dlg.find('.up').button({
					text:false,
					icons: { primary:'ui-icon-carat-1-n' }
				}).click(function(){
					var selected = visible.find(':selected');
					selected.prev().before(selected.remove());
					visible.trigger('change');
				});
				dlg.find('.down').button({
					text:false,
					icons: { primary:'ui-icon-carat-1-s' }
				}).click(function(){
					var selected = visible.find(':selected');
					selected.next().after(selected.remove());
					visible.trigger('change');
				});
				dlg.find('.add').button({
					text:false,
					icons: { primary:'ui-icon-carat-1-w' }
				}).click(function(){
					var selected = other.find(':selected');
					visible.append(selected.remove());
					visible.trigger('change');
					other.trigger('change');
				});
				dlg.find('.del').button({
					text:false,
					icons: { primary:'ui-icon-carat-1-e' }
				}).click(function(){
					var selected = visible.find(':selected');
					other.append(selected.remove());
					visible.val(visible.find('option:first-child').attr('value')).focus();
					visible.trigger('change');
					other.trigger('change');
				});
				dlg.find('.sort_field').selectmenu({ 
					width:'auto',
					position: { my: 'left bottom', at: 'left top' }
				});
				dlg.find('.sort_dir').selectmenu({ 
					width:'auto',
					position: { my: 'left bottom', at: 'left top' }
				});
				dlg.find('.records_on_page').selectmenu({
					width:'auto',
					position: { my: 'left bottom', at: 'left top' }					
				});
				dlg.keydown(function(e){
					if (e.keyCode == 13) {
						dlg.parent().find('.ui-dialog-buttonset button:eq(0)').click();
						return false;
					}
				});
			},
			open : function() {
				var dlg = $(this);
				dlg.find('.up, .down, .add, .del').button('disable');
				var visibleNames = [];
				var visible = dlg.find('.visible select');
				visible.html('');
				$.each(view.fields,function(){
					visible.append($('<option></option>').attr('value',this.name).html(this.title));
					visibleNames.push(this.name);
				});
				var other = dlg.find('.other select');
				other.html('');
				$.each(view.allfields,function(){
					if (visibleNames.indexOf(this.name)<0) {
						other.append($('<option></option>').attr('value',this.name).html(this.title));
					}
				});
				dlg.find('.sort_field').val( grid.sort_field ).selectmenu('refresh');
				dlg.find('.sort_dir').val( grid.sort_dir=='a' ? 0 : 1 ).selectmenu('refresh');
				dlg.find('.records_on_page').val( grid.recs_on_page ).selectmenu('refresh');
			},
			buttons: {
				'Сохранить': function() {
					$(this).dialog('close');
					var fields = [];
					var sort = 0;
					$(this).find('.visible select option').each(function(){
						fields.push({field_name:$(this).val(), sort_order:++sort});
					});
					$(this).find('.other select option').each(function(){
						fields.push({field_name:$(this).val(), sort_order:0});
					});
					var settings = {
						view_id: viewId,
						sort_field: $(this).find('.sort_field').val(),
						sort_dir: $(this).find('.sort_dir').val(),
						records_on_page: $(this).find('.records_on_page').val()
					};
					call('admin.doRelatedActions',{id1:'save_view_settings', params1:settings, id2:'add_view_settings_field', bulkParams2:fields, idName:'settings_id' }).done(function(){  
						call('admin.getView',{id:viewId}).done(function(v){
							view = v;
							grid.recs_on_page = v.records_on_page;
							grid.sort_field = v.sort_field;
							grid.sort_dir = v.sort_dir ? 'd' : 'a';
							grid.refresh();
						});
					});
				},
				'Сбросить': function() {
					$('#list_settings').dialog('close');
					call('admin.doAction',{ id:'del_view_settings',params:{view_id:viewId} }).done(function(){
						call('admin.getView',{id:viewId}).done(function(v){
							view = v;
							grid.recs_on_page = default_recs_on_page;
							grid.sort_field = v.sort_field;
							grid.sort_dir = v.sort_dir ? 'd' : 'a';
							grid.refresh();
						});						
					});
				},
				'Отменить': function() {
					$('#list_settings').dialog('close');
				}
			}
		});
	}
};

function del() {
	var ids = grid.getSelected();
	var params = [];
	for (var i=0; i<ids.length; ++i) {
		params.push({ '{$view.primary_key_field}': ids[i] });
	}
	confirmBox(
		'Вы уверены, что хотите удалить отмеченные записи?',
		'Подтвердите удаление',
		function() {
			call('admin.doDelete',{ 'aid':'{$view.del_action}', 'params':params }).done(function(){ refresh(); });
		}
	);
}

$(function() {
	$('#del').button( { 
		text: 'Удалить',
		icons: { primary:"ui-icon-trash" }
	});
	
	$('#add').button( { 
		text: 'Добавить',
		icons: { primary:"ui-icon-plusthick" }
	});
	
	$('#refresh').button( { 
		text: 'Обновить',
		icons: { primary:"ui-icon-arrowrefresh-1-e" }
	}).click(function(){
		grid.refresh();
		$('#actionsOnMultiple').toggle(false);		
	});
	
	$('#do_import').button( { 
		text: 'Импорт',
		icons: { primary:"ui-icon-arrowreturnthick-1-e" }
	}).click(function(){
		window.location = 'import_csv.php?aid=import_csv&vid={$view.id}&referer={$smarty.server.REQUEST_URI|escape:url}';			
	});

	$('#settings').button( { 
		text: false,
		icons: { primary:"ui-icon-gear" }
	}).click(function(){
		Settings.open();
	});
	
	$('#toolbar').show();
	Filters.init(actveFilter?actveFilter.id:false);
});
